//
//  QCWKWebViewJSHanlder.m
//  KDFDApp
//
//  Created by haoran on 2017/8/22.
//  Copyright © 2017年 cailiang. All rights reserved.
//

#import "FQWKWebViewJSHanlder.h"
#import "UIView+Additions.h"
#import <NSObject+YYModel.h>
#import "FQWebCanGobackAction.h"
#import "FQPopWindowAction.h"
#import "FQWebGoBackAction.h"
@interface FQWKWebViewJSHanlder()
@property (nonatomic, strong) QCWKWebViewJSRequestEntity *jsEntity;
@property (nonatomic, copy) NSString *mainHost;
@property (nonatomic, strong) NSArray *main_hosts;

@property (nonatomic, strong) NSArray *interceptorArray;
@end
@implementation FQWKWebViewJSHanlder
#pragma mark - WKScriptMessageHandler js调用原生代理事件
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{  
    NSLog(@"js调用原生>>>>>>>>>>%@>>>>>>>%@",message.body,message.webView.URL.absoluteString);
    if ([message.name isEqualToString:@"QCJSInterface"]) {
#if DEBUG
        [self startAction:[QCWKWebViewJSRequestEntity yy_modelWithDictionary:message.body]];
#else
//         NSURL *url =  message.webView.URL;
//        //检测host
//        [self checkHostWithUrl:url Message:message];
         [self startAction:[QCWKWebViewJSRequestEntity yy_modelWithDictionary:message.body]];
#endif
    }
}

#pragma mark - 检测Host
//- (void)checkHostWithUrl:(NSURL *)url Message:(WKScriptMessage *)message{
//
//    _mainHost = [NSUSER_DEFAULT objectForKey:@"main_host"];
//    _main_hosts = [NSUSER_DEFAULT objectForKey:@"main_hosts"];
//
//    //单个host
//    if (_mainHost && ![_mainHost isEqual:@""] && [url.host containsString:_mainHost]) {
//        [self startAction:[QCWKWebViewJSRequestEntity kd_modelWithDictionary:message.body]];
//        return;
//    }
//    //v3.2.0 新增host数组
//    __block NSInteger hostsNum = 0;
//    if (_main_hosts && [_main_hosts isKindOfClass:[NSArray class]] && _main_hosts.count > 0) {
//        [_main_hosts enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (obj && [obj isKindOfClass:[NSDictionary class]] && obj[@"host"] && ![obj[@"host"] isEqual:@""]) {
//                if ([url.host containsString:obj[@"host"]]) {
//                    hostsNum +=1;
//                    [self startAction:[QCWKWebViewJSRequestEntity kd_modelWithDictionary:message.body]];
//                    *stop = true;
//                }
//            }
//        }];
//    }
//
//    if (hostsNum == 0) {
//        //检测interceptor
//        [self checkInterceptorWithUrl:url Message:message];
//    }
//}

#pragma mark - 检测interceptor
//- (void)checkInterceptorWithUrl:(NSURL *)url Message:(WKScriptMessage *)message {
//
//    _interceptorArray = [NSUSER_DEFAULT objectForKey:@"interceptor"];
//
//    __block NSInteger num = 0;
//    __block NSInteger succeed = 0;
//
//    if (_interceptorArray && [_interceptorArray isKindOfClass:[NSArray class]] && [_interceptorArray count] > 0) {
//        [_interceptorArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (obj && [obj isKindOfClass:[NSDictionary class]] && obj[@"host"] && ![obj[@"host"] isEqual:@""]) {
//                if ([url.host containsString:obj[@"host"]]) {
//                    num+=1;
//                    BOOL result = [self beforeStartAction:message.body methodArray:obj[@"methodList"] ? : @[]];
//                    succeed = result ? succeed+1 : succeed;
//                }
//            }
//        }];
//    }
//    if (num == 0) {
//        [self callJsFail:message.body[@"callback"] code:ENUM_NOMethod message:@"方法不支持"];
//    }
//    if (succeed == 0) {
//        [self callJsFail:message.body[@"callback"] code:ENUM_NOMethod message:@"方法不支持"];
//    }
//}

#pragma mark - 处理异常
- (void)callJsFail:(NSString *)callback code:(Code)code message:(NSString *)message {
    FQWKWebResponseEntity *resp = [FQWKWebResponseEntity getResponse];
    resp.callbackid = callback;
    resp.data.code = code;
    resp.data.message = message;
    [self doWkWebViewCallback:resp];
}

//#pragma mark - 分发事件前的逻辑处理
//- (BOOL)beforeStartAction:(id)message methodArray:(NSArray *)methodArray{
//    QCWKWebViewJSRequestEntity *requestEntity = [QCWKWebViewJSRequestEntity yy_modelWithDictionary:message];
//    __block NSInteger succeed = 0;
//    if (methodArray && [methodArray isKindOfClass:[NSArray class]] && [methodArray count] > 0) {
//        [methodArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if ([requestEntity.method isEqual:obj]) {
//                succeed += succeed;
//                [self startAction:requestEntity];
//            }
//        }];
//    }
//
//    return succeed ? false : true;
//}
#pragma mark - 在这里处理分发事件
- (void)startAction:(QCWKWebViewJSRequestEntity *)requestEntity{
    id actionMethod = [_methodMap objectForKey:requestEntity.method];
    if (actionMethod) {
//        WEAKSELF
        if ([actionMethod respondsToSelector:@selector(setWebView:)]) {
            [actionMethod setWebView:self.webView];
        }
        [actionMethod action:requestEntity andCallbackBlock:^(FQWKWebResponseEntity *response) {
            [self doWkWebViewCallback:response];
        }];
    }else{
        [self callJsFail:requestEntity.callback code:ENUM_NOMethod message:@"iOS客户端无此API!请核对"];
    }
}

- (void)doWkWebViewCallback:(FQWKWebResponseEntity *)response{
    NSString *json =  [response yy_modelToJSONString];
    NSString *callbackJS = [NSString stringWithFormat:@"QCJSAPI.appCallback(%@);",json];
    //回调js必须在主线程中做
    dispatch_async(dispatch_get_main_queue(), ^{
        //在执行完客户端操作之后回调js函数
        if (self.webView && self.webView.viewController) {
            [self.webView evaluateJavaScript:callbackJS completionHandler:^(id _Nullable object, NSError * _Nullable error) {
                NSLog(@"=====%@===>原生回调JS结束=====>error信息%@>>>>>%@",callbackJS,error.userInfo,json);
            }];
        }else {
            self.webView = nil;
        }
        
    });
}
- (void)registerJSApiAction{
    _methodMap = @{

                   @"popWindow":[FQPopWindowAction new],
                   @"canGoBack":[FQWebCanGobackAction new],
                   @"goBack":[FQWebGoBackAction new],

                   };
}
-(void)dealloc
{
    
}
@end
